var takeHomeworkSuccess = false;

//监听插件发过来的消息
chrome.runtime.onMessage.addListener(
  function(request, sender, sendResponse) {
    console.log(request);
    if(request.action == 'start'){
      getCount(request, sendResponse)
    }else if(request.action == 'stop'){

    }

    // sendResponse({status: 200});
});


function getCount(request, sendResponse){
  var table = document.querySelector('.table-hover');
  var count = 0;
  if(table) count = table.children[1].children.length;

  //连接backgroundJS
  var port = chrome.runtime.connect({name: 'setCount'});
  port.postMessage({count: count});

  sendResponse({count: count});
  console.log(port);
  if(count>0){
    console.log(request)
    $('body').append('<audio autoplay src="http://www.ccydesign.com/audio/5103.mp3">')
    if(request.autoGrab){
      getHomework(request)
      if(takeHomeworkSuccess) return;
    }
  }

  setTimeout(function(){
    window.location.reload();
  }, (request.time-1)*1000)
}

function getHomework(request){
    var btns = $('.btn-qiang');
    $.each(btns, function(k, v){
      var $tr = $(v).parent().parent();
      var price = parseInt($tr.children('td').eq(7).text());
      console.log(price)
      if(price>=request.startPrice && price<=request.endPrice){
        // ajaxTakeHomework($tr.find('.btn-qiang').data('id'));
        $tr.find('.btn-qiang').click();
        console.log($tr.find('.btn-qiang'));
        console.log('click')
        takeHomeworkSuccess = true;
      }
      sendEmail({
        title: $tr.children('td').eq(4).text(),
        detail: $tr.html()
      });
    })
}

function ajaxTakeHomework(id){
    $.ajax({
        url: 'http://fuwu.jikexueyuan.com/homework/take-homework',
        type: 'POST',
        dataType: 'json',
        data: {
            id: id
        },
        async: false,
        success: function(data){
            if(data.error === 0){
                alert('抢单成功');
                window.location.href = window.APP_URL+'homework/'+id+'/correct';
            } else {
                alert(data.message);
            }
        }
    });
}
function sendEmail(data){
  console.log(data)
  $.ajax({
    url: 'http://localhost:18080/email/jike', //
    type: 'GET',
    dataType: 'json',
    data: {title: data.title, detail: data.detail},
    success: function(data){
      if(data.statCode == 200){
        console.log('已发送邮件')
      }
    }
  })
}
function sendEmail2(data){
  console.log(data)
  var params = '?title='+data.title+'&detail='+data.detail;
  var xhr = new XMLHttpRequest();
  xhr.open("GET", "http://localhost:18080/email/jike"+params, true);
  xhr.onreadystatechange = function() {
    if (xhr.readyState == 4) {
      // JSON.parse 不执行攻击者的脚本。
      // var resp = JSON.parse(xhr.responseText);
      console.log(xhr.responseText)
    }
  }
  xhr.send();
}



// <tr>
//     <td>67524</td>
//     <td>
//         <a href="javascript:;" class="btn default btn-xs green btn-qiang" data-id="67524">
//                                 抢单
//                             </a>
//     </td>
//     <td><span class="tooltips" data-placement="top" title="" data-original-title="Web大前端工程师">Web大前端工程师</span></td>
//     <td>就业班</td>
//     <td><span class="tooltips" data-placement="top" title="" data-original-title="用JS开发简易计算器">用JS开发简易计算器</span></td>
//     <td>
//         牛海蓉
//     </td>
//     <td>V1</td>
//     <td>10.00</td>
//     <td>
//         <span class="label text-danger">
//                             未批改
//                             </span>
//     </td>
//     <td>2016-09-13 14:38:17</td>
// </tr>
